import { create } from 'zustand';
import { devtools, subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { AuthStore } from './types';

const initialState: AuthState = {
  user: null,
  isAuthenticated: false,
  loading: false,
  error: null,
};

export const useAuthStore = create<AuthStore>()(
  subscribeWithSelector(
    devtools(
      immer((set, get) => ({
        // 初始状态
        ...initialState,

        // Actions
        login: async (email: string, password: string) => {
          set((state) => {
            state.loading = true;
            state.error = null;
          });

          try {
            // 模拟 API 调用
            const response = await new Promise<User>((resolve) => 
              setTimeout(() => {
                resolve({
                  id: 1,
                  name: 'Test User',
                  email: email,
                });
              }, 1000)
            );

            set((state) => {
              state.user = response;
              state.isAuthenticated = true;
              state.loading = false;
            });
          } catch (error) {
            set((state) => {
              state.error = error instanceof Error ? error.message : '登录失败';
              state.loading = false;
            });
          }
        },

        logout: () => {
          set((state) => {
            state.user = null;
            state.isAuthenticated = false;
          });
        },

        setUser: (user) => {
          set((state) => {
            state.user = user;
            state.isAuthenticated = !!user;
          });
        },

        clearError: () => {
          set((state) => {
            state.error = null;
          });
        },

        reset: () => {
          set(initialState);
        },
      }))
    )
  )
); 